package com.wk.note;

/**
 * @author WK
 * @version 1.0
 * @date 2024-07-11 19:51
 */
//package com.example.conceptnotebookjava;
//package com.example.conceptnotebookjava;
//package com.example.conceptnotebookjava;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NoteFileManager {

    private static final String NOTES_DIRECTORY = "notes/";
    private static final String TEMP_PREFIX = "temp_";

    public static void createTempNoteFile(Note note) {
        // Generate temporary filename based on current timestamp
        String filename = TEMP_PREFIX + System.currentTimeMillis() + ".md";
        Path tempFilePath = Paths.get(NOTES_DIRECTORY + filename);

        // Write content to temporary file
        try (FileWriter writer = new FileWriter(tempFilePath.toString())) {
            writer.write("title: " + note.getTitle() + "\n");
            writer.write("---\n");
            writer.write(note.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Save filename and tags to database as temporary
        saveTempNoteMetadata(filename, note.getTags());
    }

    private static void saveTempNoteMetadata(String filename, String tags) {
        String insertSQL = "INSERT INTO notes (filename, tags) VALUES (?, ?)";
        try (Connection conn = DriverManager.getConnection(H2Database.DB_URL, H2Database.DB_USERNAME, H2Database.DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
            pstmt.setString(1, filename);
            pstmt.setString(2, tags);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void saveNote(Note note) {
        // Generate final filename based on current timestamp or other criteria
        String finalFilename = System.currentTimeMillis() + ".md";
        Path finalFilePath = Paths.get(NOTES_DIRECTORY + finalFilename);
        Path tempFilePath = Paths.get(NOTES_DIRECTORY + note.getFilename());

        try {
            Files.move(tempFilePath, finalFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Update filename in database from temporary to final
        updateNoteFilename(note.getFilename(), finalFilename);
    }

    private static void updateNoteFilename(String tempFilename, String finalFilename) {
        String updateSQL = "UPDATE notes SET filename = ? WHERE filename = ?";
        try (Connection conn = DriverManager.getConnection(H2Database.DB_URL, H2Database.DB_USERNAME, H2Database.DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
            pstmt.setString(1, finalFilename);
            pstmt.setString(2, tempFilename);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Note> loadAllNotes() {
        List<Note> notes = new ArrayList<>();
        String selectSQL = "SELECT id, filename, tags FROM notes";
        try (Connection conn = DriverManager.getConnection(H2Database.DB_URL, H2Database.DB_USERNAME, H2Database.DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(selectSQL)) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Long id = rs.getLong("id");
                String filename = rs.getString("filename");
                String tags = rs.getString("tags");
                // Read content from Markdown file
                String content = readNoteContent(filename);
                // Extract title from content (if needed)
                String title = extractTitle(content);
                // Extract category (if needed)
                String category = extractCategory(content);

                Note note = new Note(id, filename, title, content, tags, category);
                notes.add(note);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return notes;
    }

    private static String extractTitle(String content) {
        // 简单示例：从Markdown格式的内容中提取标题
        int titleStart = content.indexOf("title:");
        if (titleStart != -1) {
            int titleEnd = content.indexOf("\n", titleStart);
            if (titleEnd != -1) {
                return content.substring(titleStart + 6, titleEnd).trim();
            }
        }
        return "";
    }

    private static String extractCategory(String content) {
        // 简单示例：从Markdown格式的内容中提取类别
        // 假设类别信息在内容的特定位置或格式中
        // 这里可以根据实际情况进行更复杂的处理
        // 这里只是简单示例，实际场景可能需要更复杂的逻辑来提取类别信息
        return "Default Category"; // 默认返回一个类别
    }


    private static String readNoteContent(String filename) {
        Path filePath = Paths.get(NOTES_DIRECTORY + filename);
        try {
            return Files.readString(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    // Additional methods for updating, deleting notes as needed
}
